<template>
  <div class="Detail">
    <van-nav-bar
      title="商品详情"
      left-text="返回"
      left-arrow
      @click-left="back"
    />
    <div class="produ-img">
      <img :src="detailData.large_img" alt="" />
    </div>

    <div class="pro-title">
      <div class="pro-name">
        <div class="pro-names">
          <span>{{ detailData.name }}</span>
          <p>{{ detailData.enname }}</p>
        </div>
        <div class="pro-price">{{ detailData.price }}</div>
      </div>
      <!-- 描述 -->
      <div class="pro-title-top">
        <div v-for="(item, k) in detailData.desc" :key="k">
          {{ k + 1 }}、{{ item }}
        </div>
      </div>
      <div class="pro-title-bot" @click="showPopup">立即定制</div>

      <div class="van-box">
        <van-popup v-model="show" position="bottom" :style="{ height: '60%' }">
          <!-- 商品名称 -->
          <div class="box-name">
            <div class="name-box">
              <span>{{ detailData.name }}</span>
              <p>{{ detailData.enname }}</p>
            </div>
            <div class="pro-price">{{ detailData.price }}</div>
          </div>
          <!-- 规格 -->
          <div class="rules">
            <div
              class="ruls"
              v-for="(v1, i1) in detailData.rulesData"
              :key="i1"
            >
              <div class="rule-title">{{ v1.title }}</div>
              <div class="rule-items">
                <div
                  :class="{ active: v1.currentIndex === i2 }"
                  v-for="(v2, i2) in v1.rule"
                  :key="i2"
                  @click="selectRule(v1, i2)"
                >
                  {{ v2.title }}
                </div>
              </div>
            </div>
          </div>
          <div class="choice">
            <div class="choicesum">选择数量</div>
            <van-stepper
              v-model="value"
              theme="round"
              button-size="22"
              max="12"
              disable-input
            />
          </div>
          <van-goods-action>
            <van-goods-action-icon color="#8c9198" @click="goshopbag" icon="cart" text="购物车" :badge="shopbagCount > 0 ? shopbagCount : ''" />
            <van-goods-action-icon
              icon="like"
              :text="likeStatus ? '已收藏' : '收藏'"
              :color="likeStatus ? '#05a1f4' : '#8c9198'"
              @click="likeAndNotLike"
            />
            <van-goods-action-button
              color="#6bc8f9"
              type="warning"
              text="加入购物车"
              @click="addshopbag"
            />
            <van-goods-action-button
              color="#05a1f4"
              type="danger"
              text="立即购买"
              @click="goshopbag"
            />
          </van-goods-action>
        </van-popup>
      </div>
    </div>
  </div>
</template>

<script>
import "../assets/less/Detail.less";
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      show: false,
      //数量
      value: 1,
      //商品详情数据
      detailData: {},
      //商品pid
      pid: "",
      //收藏状态
      likeStatus: false,
    };
  },
  created() {
    //截取pid
    this.pid = this.$route.params.pid;

    this.getDetailData();

    this.getLikeProduct();

    this.getShopbagCount();
  },
  computed: {
    ...mapState(["shopbagCount", "isLoadShopbagCount"]),
  },
  methods: {
    ...mapMutations(["changeShopbagCount", "changeIsLoadShopbagCount"]),

    showPopup() {
      this.show = true;
    },
    //返回上一级
    back() {
      this.$router.go(-1);
    },
    
    //获取商品详情数据
    getDetailData() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.axios({
        method: "GET",
        url: this.baseUrl + "/productDetail",
        params: {
          appkey: this.appkey,
          pid: this.pid,
        },
      })
        .then((res) => {
          // console.log("res getDetailData=>", res);
          this.$toast.clear();
          if (res.data.code === 600) {
            let data = res.data.result[0];
            //处理res
            let rules = ["cream", "milk", "sugar", "tem"];

            //保存处理规格数据
            data.rulesData = [];

            rules.forEach((v) => {
              //如果不存在规格，则不添加到data.rulesData
              if (!data[v]) {
                return;
              }
              //切割 默认奶油/无奶油
              let rulesText = data[v].split("/");
              // console.log(rulesText)

              let currentRule = {
                title: data[v + "_desc"],
                currentIndex: 0,
                rule: [],
              };

              rulesText.forEach((item) => {
                let o = {
                  title: item,
                };
                currentRule.rule.push(o);
              });
              data.rulesData.push(currentRule);
            });
            //处理商品描述信息
            data.desc = data.desc.split(/\n/);

            // console.log('data ==>', data);

            this.detailData = data;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    //选择规格
    selectRule(item, index) {
      //如果点击相同rule
      if (item.currentIndex === index) {
        return;
      }
      item.currentIndex = index;
    },
    //收藏或者取消收藏
    likeAndNotLike() {
      if (this.likeStatus) {
        //取消收藏
        this.notLike();
      } else {
        //收藏
        this.like();
      }
    },
    //收藏
    like() {
      let tokenString = this.$cookies.get("tokenString");
      // console.log('tokenString ===>' ,tokenString)

      if (!tokenString) {
        //浏览器token不存在
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "POST",
        url: this.baseUrl + "/like",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          // console.log('res ==>',res);
          this.$toast.clear();

          if (res.data.code === 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            //未登录跳转到登录页面
            return this.$router.push({ name: "Login" });
          }
          if (res.data.code === 800) {
            //已收藏
            this.likeStatus = true;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    //取消收藏
    notLike() {
      let tokenString = this.$cookies.get("tokenString");
      // console.log('tokenString ===>' ,tokenString)

      if (!tokenString) {
        //浏览器token不存在
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "POST",
        url: this.baseUrl + "/notlike",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          // console.log('res ==>',res);
          this.$toast.clear();

          if (res.data.code === 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            //未登录跳转到登录页面
            return this.$router.push({ name: "Login" });
          }
          if (res.data.code === 900) {
            if (res.data.result === 1) {
              ///取消收藏
              this.likeStatus = false;
            }
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    //查询当前收藏商品
    getLikeProduct() {
      let tokenString = this.$cookies.get("tokenString");
      // console.log('tokenString ===>' ,tokenString)

      if (!tokenString) {
        //浏览器token不存在
        return;
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "GET",
        url: this.baseUrl + "/findlike",
        params: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          // console.log('res ==>',res);
          this.$toast.clear();

          if (res.data.code === 700) {
            //未登录
            return;
          }
          if (res.data.code === 1000) {
            //已收藏
            if (res.data.result.length > 0) {
              this.likeStatus = true;
            }
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    //添加购物车
    addshopbag() {
      let tokenString = this.$cookies.get("tokenString");
      // console.log('tokenString ===>' ,tokenString)

      if (!tokenString) {
        //浏览器token不存在
        return this.$router.push({ name: "Login" });
      }

      let rules = [];
      this.detailData.rulesData.forEach((v) => {
        rules.push(v.rule[v.currentIndex].title);
      });
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "POST",
        url: this.baseUrl + "/addShopcart",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
          count: this.value,
          rule: rules.join("/"),
        },
      })
        .then((res) => {
          console.log("res ==>", res);
          this.$toast.clear();

          if (res.data.code === 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            //未登录跳转到登录页面
            return this.$router.push({ name: "Login" });
          }
          if (res.data.code === 3000) {
            if (res.data.status === 1) {
              //提交mutations修改shopbagCount
              this.changeShopbagCount(this.shopbagCount + 1);
              this.$toast({
                message: res.data.msg,
                forbidClick: true,
                duration: 1000,
              });
            }else{
              this.$toast({
                message: res.data.msg,
                forbidClick: true,
                duration: 1000,
              });
            }

          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    //跳到购物车页面
    goshopbag() {
      this.addshopbag();
      this.$router.push({ name: "Shopping" });
    },
    //获取购物袋的数目(不是商品总数量)
    getShopbagCount() {
      if (this.isLoadShopbagCount) {
        //Detail 已经加载过购物袋数量, 不再请求
        return;
      }
      let tokenString = this.$cookies.get("tokenString");
      // console.log("tokenString ==>",tokenString)

      if (!tokenString) {
        console.log("浏览器token不存在");
        return;
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

            this.axios({
        //请求方式
        method: "GET",
        url: this.baseUrl + "/shopcartRows",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((res) => {
          console.log("res getShopcartCount ==> ", res);
          this.$toast.clear();

          //没有登录
          if (res.data.code == 700) {
            return;
          }

          if (res.data.code === 8000) {
            //提交changeShopbagCount的mutations
            this.changeShopbagCount(res.data.result);
            // console.log('this.shopbagCount ==> ', this.shopbagCount);
            this.changeIsLoadShopbagCount(true);
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    }
  },
};
</script>

<style lang="less" scoped>
</style>